package com.zywl.web.controller.sys;

import com.zywl.core.beans.AssResRel;
import com.zywl.core.beans.Association;
import com.zywl.core.beans.Role;
import com.zywl.core.beans.User;
import com.zywl.service.AssResRelService;
import com.zywl.service.AssociationService;
import com.zywl.service.UserService;
import com.zywl.utils.models.AjaxResult;
import com.zywl.utils.models.PageData;
import com.zywl.utils.models.PageResult;
import com.zywl.utils.utils.*;
import com.zywl.utils.utils.enums.LogTypeEnum;
import com.zywl.web.controller.base.BaseController;
import com.zywl.web.controller.form.AssociationForm;
import com.zywl.web.controller.form.Userform;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/association")
public class AssociationController extends BaseController {
    @Autowired
    private AssociationService associationService;
    @Autowired
    private AssResRelService assResRelService;
    @Autowired
    private UserService userService;

    @GetMapping("/associationListPage")
    public ModelAndView associationListPage() {
        ModelAndView mav = new ModelAndView("association/associationListPage");
        return mav;
    }


    @PostMapping("/getAssociationList")
    public PageResult getAssociationList(HttpServletRequest request, PageData pageData) {

        Map<String, Object> condition = MapUtil.changeMap(request.getParameterMap());
        PageResult pageResult = null;
        try {
            pageResult = putToResult(associationService.getPageInfo(condition, pageData));
        } catch (Exception e) {
            logger.error("获取会员列表异常", e);
        }
        return pageResult;
    }

    @GetMapping("/associationSubmitPage")
    public ModelAndView associationSubmitPage(String id, HttpSession session) {
        ModelAndView mav = new ModelAndView("association/associationSubmitPage");
        try {
            if (StringUtils.isNotEmpty(id)) {
                Association association = associationService.getById(Long.parseLong(id));
                mav.addObject("association", association);

                if(association != null){
                    //查询协会下拥有的权限
                    List<AssResRel> assResRels = assResRelService.getByAssId(Long.parseLong(id));
                    StringBuilder sb = new StringBuilder();
                    for (AssResRel assResRel:assResRels){
                        sb.append(Constants.STRING_SPLIT);
                        sb.append(assResRel.getArsResId());
                    }
                    if (assResRels != null && !assResRels.isEmpty()) {
                        sb.append(Constants.STRING_SPLIT);
                        sb.append(Constants.RESOURCE_ROOT_PARENT);
                    }
                    if (sb.length() > 0) {
                        mav.addObject("ids", sb.deleteCharAt(0).toString());
                    }
                }
            }
        } catch (Exception e) {
            logger.error("获取数据异常", e);
        }
        return mav;
    }

    @PostMapping("/associationSubmit")
    public AjaxResult associationSubmit(HttpServletRequest request, AssociationForm form) {
        AjaxResult ar = new AjaxResult();
        if (form != null) {
            Association association = null;
            String old = null;
            Date date = new Date();
            try {
                if (form.getAssId() != null) {
                    association = associationService.getById(form.getAssId());
                    old = association.getAssName();
                    form.setAssStt(association.getAssStt());
                    form.setAssCreateTime(association.getAssCreateTime());
                } else {
                    association = new Association();
                    form.setAssStt("0");
                    form.setAssCreateTime(date);

                    //查询协会是否已经从存在
                    Map<String, Object> condition = new HashMap<>();
                    condition.put("assName",association.getAssName());
                    condition.put("assStt","0");
                    int count = associationService.getCountByParams(condition);
                    if(count > 0){
                        ar.error("该协会已存在，请修改");
                        return ar;
                    }
                }

                form.setAssModifyTime(date);
                BeanUtils.copyProperties(form, association);

                if (form.getAssId() == null) {
                    associationService.save(association,form.getIds());
                } else {
                    associationService.update(association,form.getIds());
                }
            } catch (Exception e) {
                logger.error("提交协会信息异常", e);
                ar.error("提交协会信息异常", e);
                return ar;
            }

            if (form.getAssId() == null) {
                saveLog(request, LogTypeEnum.ASSOCIATION.getKey(), "协会新增-" + form.getAssName());
                ar.success("新增成功");
            } else if (old != null && !old.equals(form.getAssName())) {
                saveLog(request, LogTypeEnum.ASSOCIATION.getKey(), "协会修改-" + old + "→" + form.getAssName());
                ar.success("修改成功");
            } else {
                saveLog(request, LogTypeEnum.ASSOCIATION.getKey(), "协会修改-" + form.getAssName());
                ar.success("修改成功");
            }
        } else {
            ar.error("提交失败，参数为空");
        }
        return ar;
    }

    @PostMapping("/associationDelete")
    public AjaxResult associationDelete(HttpServletRequest request, Long id) {
        AjaxResult ar = new AjaxResult();
        try {
            Association association = associationService.getById(id);
            String associationNickName = association.getAssName();
            association.setAssStt("1");
            associationService.update(association);//逻辑删除用户
            saveLog(request, LogTypeEnum.ASSOCIATION.getKey(), "协会删除-" + associationNickName);
            ar.success("删除成功");
        } catch (Exception e) {
            ar.error("删除协会异常", e);
            logger.error("删除协会异常", e);
        }
        return ar;
    }

    @PostMapping("/updateState")
    public AjaxResult updateState(HttpServletRequest request, Long id,String stt) {
        AjaxResult ar = new AjaxResult();
        try {
            Association association = associationService.getById(id);
            String associationNickName = association.getAssName();
            association.setAssStt(stt);
            associationService.update(association);
            if("0".equals(stt)){
                saveLog(request, LogTypeEnum.ASSOCIATION.getKey(), "协会启用-" + associationNickName);
            }else{
                saveLog(request, LogTypeEnum.ASSOCIATION.getKey(), "协会禁用-" + associationNickName);
            }
            ar.success("操作成功");
        } catch (Exception e) {
            ar.error("操作协会异常", e);
            logger.error("操作协会异常", e);
        }
        return ar;
    }


    /**
     * 上传头像照片
     * @param request
     * @param multipartRequest
     * @return
     */
    @PostMapping("uploadFile")
    public Map<String,Object> uploadFile(HttpServletRequest request, DefaultMultipartHttpServletRequest multipartRequest){
        CommonsMultipartFile file = (CommonsMultipartFile)multipartRequest.getFile("file");
        Map<String, Object> map = new HashMap();
        try {
            StringBuffer stringBuffer=new StringBuffer();
            stringBuffer.append(File.separator);
            stringBuffer.append("static");
            stringBuffer.append(File.separator);
            stringBuffer.append("file");
            stringBuffer.append(File.separator);
            stringBuffer.append("wxapiclientkey");
            stringBuffer.append(File.separator);
            stringBuffer.append(file.getOriginalFilename());
            map.put("path",stringBuffer.toString());

//            StringBuffer sb=new StringBuffer();
//            sb.append("xhgl");
//            sb.append(stringBuffer.toString());

            String filePath = FileUtil.getFileRealPathForServer(request, stringBuffer.toString());
            File newFile = FileUtil.newFile(filePath);
            file.transferTo(newFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

}
